<template>
  <div class="user-avatar" :style="avatarStyle">
    <span v-if="!avatarUrl">{{ userInitials }}</span>
  </div>
</template>

<script>
export default {
  name: 'UserAvatar',
  props: {
    user: {
      type: Object,
      required: true
    },
    size: {
      type: Number,
      default: 40
    }
  },
  computed: {
    avatarUrl() {
      return this.user.avatar || null;
    },
    userInitials() {
      if (!this.user.username) return '';
      return this.user.username.charAt(0).toUpperCase();
    },
    avatarStyle() {
      return {
        width: `${this.size}px`,
        height: `${this.size}px`,
        backgroundImage: this.avatarUrl ? `url(${this.avatarUrl})` : null,
        backgroundColor: this.avatarUrl ? 'transparent' : this.getRandomColor(this.user.id || this.user.username),
        fontSize: `${this.size / 2}px`
      };
    }
  },
  methods: {
    getRandomColor(seed) {
      const colors = [
        '#f44336', '#e91e63', '#9c27b0', '#673ab7', '#3f51b5',
        '#2196f3', '#03a9f4', '#00bcd4', '#009688', '#4caf50',
        '#8bc34a', '#cddc39', '#ffc107', '#ff9800', '#ff5722'
      ];
      
      // 使用简单的哈希函数为用户生成一致的颜色
      let hash = 0;
      const str = String(seed);
      for (let i = 0; i < str.length; i++) {
        hash = str.charCodeAt(i) + ((hash << 5) - hash);
      }
      
      return colors[Math.abs(hash) % colors.length];
    }
  }
};
</script>

<style scoped>
.user-avatar {
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: bold;
  background-size: cover;
  background-position: center;
}
</style> 